package org.projectback.listener;

import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.projectback.entity.AccountEntity.dataTransferObject.emailMessageDTO;
import org.projectback.utils.ThreadPoolUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.support.ListenerExecutionFailedException;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
@RabbitListener(queues = "email")
@Slf4j
public class emailQueueListener {
    @Resource
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Resource
    private ThreadPoolUtils threadPoolUtils;

    /**
     * 邮件队列消费者
     *
     * @param emailMessageDTO 封装过的实体类
     */
    @RabbitHandler
    public void receiveEmail(emailMessageDTO emailMessageDTO, Channel channel) {
        Integer code = emailMessageDTO.getCode();
        String type = emailMessageDTO.getType();
        String email = emailMessageDTO.getEmail();
        //不关心返回结果，使用execute 若是方法有返回值或者需要处理方法中的异常 使用submit 并使用Future对象接收返回结果或异常
        threadPoolUtils.executorService.execute(() -> {
            SimpleMailMessage message = switch (type) {
                case "register" ->
                        getMailMessage("欢迎注册", "您的邮件注册码为" + code + "有效时间为1分钟 请尽快前往输入", email);
                case "reset" ->
                        getMailMessage("重置密码", "您的验证码为" + code + "正在进行重置密码操作,若不是本人请无视\n验证码有效时间为三分钟请尽快修改密码！", email);
                default -> null;
            };
            if (message != null) {
                try {
                    javaMailSender.send(message);
                } catch (Exception exception) {
                    if (exception instanceof MailException | exception instanceof ListenerExecutionFailedException) {
                        log.warn(exception.getMessage());
                        try {
                            channel.basicReject(exception.hashCode(), false);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    if (exception instanceof NullPointerException) {
                        log.warn(exception.getMessage());
                    }
                }
            }
        });

    }

    private SimpleMailMessage getMailMessage(String sub, String text, String email) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject(sub);
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setText(text);
        simpleMailMessage.setTo(email);
        return simpleMailMessage;
    }
}
//